var logger = require('../utils/log4js').app

const ChatService = require('./chat')
const chat = new ChatService('chatroom')

var debug = {
  len: data => { return JSON.stringify(data).length }
}

module.exports = (server) => {
  var io = require('socket.io')(server)
  io.path('/')

  io.on('connection', socket => {
    logger.info(socket.id, 'User Join')

    socket.emit('control', true, console.log)

    socket.on('chatmessage', ({ user, message, dtype, data }) => {
      logger.info(socket.id, 'Message Received:', debug.len({ user, message, dtype, data }))

      chat.saveMessage({ user, message, dtype, data }).then(() => {
        logger.debug(socket.id, 'Message Saved:', debug.len({ user, message, dtype, data }))
      }).catch(logger.error)

      io.emit('chatmessage', { user, message, dtype: dtype || 'text', data: data || null })
      logger.debug(socket.id, 'Message Pub:', debug.len({ user, message, dtype: dtype || 'text', data: data || null }))
    })

    socket.on('username', username => {
      logger.info(socket.id, 'Username Received:', debug.len(username))

      socket.broadcast.emit('chatmessage', { user: 'system', message: username + '加入了聊天！' })
      logger.debug(socket.id, 'User Join Pub    :', debug.len({ user: 'system', message: username + '加入了聊天！' }))

      chat.readMessage().then(data => {
        for (var idx = data.length - 1; idx >= 0; idx = idx - 1) {
          var item = data[idx]
          socket.emit('chatmessage', item)
          logger.debug(socket.id, 'Init Message Sent:', debug.len(item))
        }
        socket.emit('chatmessage', { user: 'system', message: '👆上集回顾' })
        logger.debug(socket.id, 'Init Message End :', debug.len({ user: 'system', message: '👆上集回顾' }))
      }).catch(logger.error)
    })
    socket.on('disconnect', reason => {
      logger.info(socket.id, 'User Leave:', reason)
    })
  })
}
